import process from 'node:process';
import { URL, fileURLToPath } from 'node:url';

import { defineConfig, loadEnv } from 'vite';

import { createViteProxy, getBuildTime } from './build/config';
import { setupVitePlugins } from './build/plugins';

export default defineConfig(configEnv => {
	const viteEnv = loadEnv(configEnv.mode, process.cwd()) as unknown as Env.ImportMeta;

	const buildTime = getBuildTime();

	const enableProxy = configEnv.command === 'serve' && !configEnv.isPreview;
	const proxyInfo = createViteProxy(viteEnv, enableProxy);
	console.log('****当前配置的代理请求Start****');
	console.log('[ proxyInfo ] >', proxyInfo);
	console.log('****当前配置的代理请求End****');
	console.log('[ configEnv ] >', viteEnv);
	return {
		base: viteEnv.VITE_BASE_URL,
		build: {
			outDir: 'qacn', //
			rollupOptions: {
				output: {
					assetFileNames: chunkInfo => {
						const name = chunkInfo.names[0];

						if (name?.endsWith('.css')) {
							return 'css/[name]-[hash].css';
						}

						const imgExts = ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp'];

						if (imgExts.some(ext => name?.endsWith(`.${ext}`))) {
							return 'images/[name]-[hash].[ext]';
						}

						if (name?.endsWith('.js')) {
							return 'js/[name]-[hash].js';
						}

						return 'assets/[name]-[hash].[ext]';
					},
					chunkFileNames: chunkInfo => {
						// 检查文件路径，如果是 pages 目录下的文件，则修改文件名和路径
						const filePath = chunkInfo.facadeModuleId;

						if (filePath) {
							// 提取文件的父文件夹作为文件名
							if (filePath.includes('/src/pages/')) {
								// 提取文件的父文件夹作为文件名
								const pageName = filePath.split('/src/pages/')[1];
								// 替换 [name] 为  name 因为vite不支持
								const newPath = pageName.replace(/\[([^\]]+)\]/g, '$1');

								const path = newPath.slice(0, newPath.lastIndexOf('/'));

								return `js/pages/${path}/[name]-[hash].js`;
							} else if (filePath.includes('/src/components/')) {
								return `js/components/[name]-[hash].js`;
							}
						}

						return 'js/[name]-[hash].js'; // 默认处理方式
					},
					manualChunks: {
						// 核心框架
						react: ['react', 'react-dom', 'react-error-boundary'],

						// 路由
						router: ['react-router-dom'],

						// 状态管理
						redux: ['redux', 'react-redux', '@reduxjs/toolkit'],

						// UI 框架
						antd: ['antd', '@ant-design/icons', '@ant-design/v5-patch-for-react-19'],

						// 动画
						motion: ['motion', 'framer-motion', 'animate.css', 'animejs'],

						// 多语言
						i18n: ['react-i18next', 'i18next'],

						// 网络请求
						network: ['axios', 'alova'],

						// 工具类
						utils: ['lodash-es', 'dayjs', 'js-cookie', 'crypto-js'],

						// 编辑器相关
						editor: [
							'@wangeditor/editor',
							'@wangeditor/editor-for-react',
							'@hufe921/canvas-editor'
						],

						// 第三方组件
						dnd: ['@dnd-kit/core', '@dnd-kit/sortable', '@dnd-kit/utilities'],
						loader: ['react-loader-spinner', 'nprogress', 'simplebar-react'],

						// 图标库
						iconify: ['@iconify/react']
					}
				}
			}
		},
		css: {
			preprocessorOptions: {
				scss: {
					additionalData: `@use "@/styles/scss/global.scss" as *;`,
					api: 'modern-compiler'
				}
			}
		},
		define: {
			BUILD_TIME: JSON.stringify(buildTime)
		},
		plugins: setupVitePlugins(viteEnv, buildTime),
		preview: {
			port: 9725
		},
		resolve: {
			alias: {
				'@': fileURLToPath(new URL('./src', import.meta.url)),
				'~': fileURLToPath(new URL('./', import.meta.url))
			}
		},
		server: {
			host: '0.0.0.0',
			open: true,
			port: 6699,
			proxy: createViteProxy(viteEnv, enableProxy),
			warmup: {
				clientFiles: ['./index.html', './src/{pages,components}/*']
			}
		}
	};
});
